package com.jeecg.teamrank.main.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtil {
	private static final HttpClient hc =  getHttpClient(); 
  
    private static HttpClient getHttpClient() {  
    	if(hc!=null){
    		return hc;
    	}
    	// 设置组件参数, HTTP协议的版本,1.1/1.0/0.9   
        HttpParams params = new BasicHttpParams();   
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);   
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");   
        HttpProtocolParams.setUseExpectContinue(params, true);      
      
        //设置连接超时时间   
        int REQUEST_TIMEOUT = 50*1000;  //设置请求超时50秒钟   
        int SO_TIMEOUT = 50*1000;       //设置等待数据超时时间50秒钟   
        //HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);  
        //HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);  
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, REQUEST_TIMEOUT);    
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);   
        
        //设置访问协议   
        SchemeRegistry schreg = new SchemeRegistry();    
        schreg.register(new Scheme("http",80,PlainSocketFactory.getSocketFactory()));   
        schreg.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));         
          
        //多连接的线程安全的管理器   
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schreg);  
        cm.setDefaultMaxPerRoute(50); //每个主机的最大并行链接数   
        cm.setMaxTotal(100);          //客户端总并行链接最大数      
          
        DefaultHttpClient httpClient = new DefaultHttpClient(cm, params);    
        return httpClient;  
    }  
	
	/**
	 * Get请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 */

	public static String getHttps(String url) {
		SSLContext ctx = null;
		try {
			ctx = SSLContext.getInstance("SSL");
			
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		// Implementation of a trust manager for X509 certificates
		X509TrustManager tm = new X509TrustManager() {

			public void checkClientTrusted(X509Certificate[] xcs, String string)
					throws CertificateException {

			}

			public void checkServerTrusted(X509Certificate[] xcs, String string)
					throws CertificateException {
			}

			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		try {
			ctx.init(null, new TrustManager[] { tm }, null);
		} catch (KeyManagementException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		SSLSocketFactory ssf = new SSLSocketFactory(ctx);
		ssf.setHostnameVerifier(new AllowAllHostnameVerifier());
		ClientConnectionManager ccm = hc.getConnectionManager();
		// register https protocol in httpclient's scheme registry
		SchemeRegistry sr = ccm.getSchemeRegistry();
		sr.register(new Scheme("https", 443, ssf));
		
		String body = null;
		try {
			// Get请求
			HttpGet httpget = new HttpGet(url);
			
			// 发送请求
			HttpResponse httpresponse = hc.execute(httpget);
			// Header[] headers = httpresponse.getAllHeaders();
			// for(int i=0; i<headers.length;i++){
			// System.out.println(headers[i]);
			// }
			// 获取返回数据
			HttpEntity entity = httpresponse.getEntity();
			body = EntityUtils.toString(entity);
			if (entity != null) {
//				entity.getContent().close(); //!!!IMPORTANT 
				entity.consumeContent();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return body;
	}

	public static String get(String url, List<NameValuePair> params) {
		String body = null;
		Logger logger = LoggerFactory.getLogger("cn.unisk.liuliang.HttpClientUtil");
		logger.debug(url);
		try {
			// Get请求
			HttpGet httpget = new HttpGet(url);
			// 设置参数
			if (params != null) {
				String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
				httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
			}
			// 发送请求
			HttpResponse httpresponse = hc.execute(httpget);
			// Header[] headers = httpresponse.getAllHeaders();
			// for(int i=0; i<headers.length;i++){
			// System.out.println(headers[i]);
			// }
			// 获取返回数据
			HttpEntity entity = httpresponse.getEntity();
			body = EntityUtils.toString(entity);
			if (entity != null) {
//				entity.getContent().close(); //!!!IMPORTANT 
				entity.consumeContent();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		logger.debug(body);
		return body;
	}

	/**
	 * // Post请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static String post(String url, List<NameValuePair> params) {
		Logger logger = LoggerFactory.getLogger("cn.unisk.liuliang.HttpClientUtil");
		logger.debug(url);
		String body = null;
		try {
			// Post请求
			HttpPost httppost = new HttpPost(url);
			
			// 设置参数
			if (params != null) {
				httppost.setEntity(new UrlEncodedFormEntity(params));
			}
			// 发送请求
			HttpResponse httpresponse = hc.execute(httppost);
			// 获取返回数据
			HttpEntity entity = httpresponse.getEntity();
			body = EntityUtils.toString(entity);		
			if (entity != null) {
//				entity.getContent().close();
				entity.consumeContent();
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			
		}
		logger.debug(body);
		return body;
	}
	
	public static void sendReport(String strURL){
		System.out.println("strURL"+strURL);
		if((strURL==null) || (strURL.trim().length()<10)){
			return;
		}
		TransThread tt = new TransThread(strURL);
		tt.start();
	}
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {		
		long start = System.currentTimeMillis();
		String jsonObj = post("http://120.52.23.131:8088/UnicomAPI/externalIntfs?method=getFreeFlow&province=guizhou&phone=15011550798&productCode=LLPF200",null);
		 jsonObj = post("http://120.52.23.131:8088/UnicomAPI/externalIntfs?method=getFreeFlow&province=guizhou&phone=15011550798&productCode=LLPF200",null);
		 jsonObj = post("http://120.52.23.131:8088/UnicomAPI/externalIntfs?method=getFreeFlow&province=guizhou&phone=15011550798&productCode=LLPF200",null);
		 System.out.println(System.currentTimeMillis()-start);
		} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}
}

class TransThread extends Thread {
	private String strURL="";
	public TransThread(String strURL) {
		this.strURL = strURL;
	}

	public void run() {
		try {			
			ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("param","{\"trans_type\":\"sms_send\",\"username\":\"15651600617\",\"msg_content\":\"826593\"}"));
				HttpClientUtil.post(strURL, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
